package com.iring.util.proxy;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

import com.iring.domain.config.prop.SIPProperties;


/**
 * hmac_sha256进行签名运算
 *
 * @author wanggan
 */
@Configuration
public class ProxyHMACUtil {

    @Autowired
    SIPProperties sipProperties;

    /**
     * 创建签名
     *
     * @param data
     *          需要进行签名的数据
     * @return  生成的签名
     */
    public String createSign(String data){
        Assert.notNull(sipProperties.getSipKey(),"sip key must not be null");
        try  {
            SecretKeySpec signingKey = new SecretKeySpec(sipProperties.getSipKey().getBytes(), "HmacSHA256");
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(signingKey);
            return byte2hex(mac.doFinal(data.getBytes())).toLowerCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        return null;

    }


    private  String byte2hex(byte[] b)
    {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b!=null && n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }
}
